# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/7/26
# @File   : R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_GZ.py
# @E-mail : zhaochen@bbdservice.com


'''eof
name:申请人近6个月内贷款、贷记卡及准贷记卡累计逾期次数校验
code:R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_GZ
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def AccOvduMonsCheckPre(*args):
    loanTabel = getTable(args[0])
    latest5Years = getTable(args[1])

    Factor1 = 0
    Factor11 = [0]
    monthToday = datetime.datetime.now().year * 12 + datetime.datetime.now().month
    monthSixMonthsAgo = monthToday - 6

    # 最近24个月还款记录 和 最近5年逾期记录 均为None 返回 None
    if loanTabel is None and latest5Years is None:
        Factor1 = None
        Factor11 = None
        return Factor1, Factor11
    # 最近24个月还款记录 为None 和 最近5年逾期记录 不为None
    elif loanTabel is None and latest5Years is not None:
        if latest5Years == [{}]:
            return Factor1, Factor11
        else:
            flag = []
            for i in latest5Years:
                try:
                    if i['month'] not in null_type_list and i['lastMonths'] not in null_type_list:
                        month = i['month']
                        monthFact = float(month[:4]) * 12 + float(month[5:])
                        lastMonths = i['lastMonths']
                        if isfloat(lastMonths) and float(lastMonths) >= 1 and float(lastMonths) <= 7:
                            if args[0] == 'ICRStdLoancardInfo002*Std':
                                if float(lastMonths) >= 3 and monthFact <= monthToday and monthFact > monthSixMonthsAgo:
                                    Factor1 += 1
                                    Factor11.append(float(lastMonths) - 2)
                            else:
                                if monthFact <= monthToday and monthFact > monthSixMonthsAgo:
                                    Factor1 += 1
                                    Factor11.append(float(lastMonths))
                        else:
                            flag.append(None)
                    else:
                        flag.append(None)
                except:
                    flag.append(None)
            if len(flag) == len(latest5Years):
                Factor1 = None
                Factor11 = None
            return Factor1, Factor11
    # 最近24个月还款记录 不为None 和 最近5年逾期记录 为None
    elif loanTabel is not None and latest5Years is None:
        if loanTabel == [{}]:
            return Factor1, Factor11
        else:
            flag = []
            for i in loanTabel:
                try:
                    if i['latest24State'] not in null_type_list:
                        latest24State = i['latest24State']
                        # 最近6个格子
                        latest6State = latest24State[::-1][:6]
                        if args[0] == 'ICRStdLoancardInfo002*Std':
                            pattern = '[3-7]'
                            r = re.compile(pattern)
                            resultResult = r.findall(latest6State)
                            if len(resultResult) != 0:
                                Factor1 += len(resultResult)
                                Factor11.append(float(max(resultResult)) - 2)
                        else:
                            pattern = '[1-7]'
                            r = re.compile(pattern)
                            resultResult = r.findall(latest6State)
                            if len(resultResult) != 0:
                                Factor1 += len(resultResult)
                                Factor11.append(float(max(resultResult)))

                except:
                    flag.append(None)
            if len(flag) == len(loanTabel):
                Factor1 = None
                Factor11 = None
            return Factor1, Factor11
    # 最近24个月还款记录 不为None 和 最近5年逾期记录 不为None
    else:
        # 处理24个月还款记录 仅存在[{}] 和 有数据的情况
        # 为[{}] 默认为0情况，故不处理
        isNone1 = False
        if loanTabel != [{}]:
            flag = []
            for i in loanTabel:
                try:
                    if i['latest24State'] not in null_type_list:
                        latest24State = i['latest24State']
                        # 最近6个格子
                        latest6State = latest24State[::-1][:6]
                        if args[0] == 'ICRStdLoancardInfo002*Std':
                            pattern = '[3-7]'
                            r = re.compile(pattern)
                            resultResult = r.findall(latest6State)
                            if len(resultResult) != 0:
                                Factor1 += len(resultResult)
                                Factor11.append(float(max(resultResult)) - 2)
                        else:
                            pattern = '[1-7]'
                            r = re.compile(pattern)
                            resultResult = r.findall(latest6State)
                            if len(resultResult) != 0:
                                Factor1 += len(resultResult)
                                Factor11.append(float(max(resultResult)))

                except:
                    flag.append(None)
            if len(flag) == len(loanTabel):
                isNone1 = True
        # 处理5年逾期记录
        isNone2 = False
        if latest5Years != [{}]:
            flag = []
            for i in latest5Years:
                try:
                    if i['month'] not in null_type_list and i['lastMonths'] not in null_type_list:
                        month = i['month']
                        monthFact = float(month[:4]) * 12 + float(month[5:])
                        lastMonths = i['lastMonths']
                        if isfloat(lastMonths) and float(lastMonths) >= 1 and float(lastMonths) <= 7:
                            if args[0] == 'ICRStdLoancardInfo002*Std':
                                if float(lastMonths) >= 3 and monthFact <= monthToday and monthFact > monthSixMonthsAgo:
                                    Factor1 += 1
                                    Factor11.append(float(lastMonths) - 2)
                            else:
                                if monthFact <= monthToday and monthFact > monthSixMonthsAgo:
                                    Factor1 += 1
                                    Factor11.append(float(lastMonths))
                        else:
                            flag.append(None)
                    else:
                        flag.append(None)
                except:
                    flag.append(None)
            if len(flag) == len(latest5Years):
                isNone2 = True

        if isNone1 and isNone2:
            Factor1 = None
            Factor11 = None
            return Factor1, Factor11
        else:
            return Factor1, Factor11


def R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_GZ():
    Factor1, Factor11 = AccOvduMonsCheckPre(*('ICRLoanInfo002*Loan', 'ICRLatest5YearOverdueDetail*Loan'))
    Factor2, Factor22 = AccOvduMonsCheckPre(*('ICRLoancardInfo002*Card', 'ICRLatest5YearOverdueDetail*Card'))
    Factor3, Factor33 = AccOvduMonsCheckPre(*('ICRStdLoancardInfo002*Std', 'ICRLatest5YearOverdueDetail*Std'))

    if Factor1 is None and Factor2 is None and Factor3 is None:
        Factor4 = None
    else:
        if Factor1 is None:
            Factor1 = 0
        if Factor2 is None:
            Factor2 = 0
        if Factor3 is None:
            Factor3 = 0
        Factor4 = Factor1 + Factor2 + Factor3
    if Factor11 is None and Factor22 is None and Factor33 is None:
        Factor5 = None
    else:
        if Factor11 is None:
            Factor11 = [0]
        if Factor22 is None:
            Factor22 = [0]
        if Factor33 is None:
            Factor33 = [0]
        Factor5 = max(max(Factor11), max(Factor22), max(Factor33))

    if Factor4 is None and Factor5 is None:
        return u'缺失值'
    else:
        if Factor4 is None:
            Factor4 = 0
        if Factor5 is None:
            Factor5 = 0
        # print 'IC16:', Factor4, Factor5
        #5、否则Factor=1 if Factor1+Factor2+Factor3 <= 2
        # and max(Factor11,Factor22,Factor33) < 2 else 0
        if Factor4 <= 2 and Factor5 < 2:
            return 1
        else:
            return 0

result = R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_GZ()